package com.lagou.edu.service.impl;

import com.lagou.edu.Account;
import com.lagou.edu.Token;
import com.lagou.edu.mapper.TokenMapper;
import com.lagou.edu.mapper.UserMapper;
import com.lagou.edu.service.AuthCodeServiceFeignClient;
import com.lagou.edu.service.UserService;
import com.lagou.edu.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AuthCodeServiceFeignClient authCodeServiceFeignClient;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenMapper tokenMapper;

    private static final String FLAG = "_";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean register(String email, String password, String code) {
        Integer validate = authCodeServiceFeignClient.validate(email, code);
        //验证码校验通过，且没有注册过
        if(validate == 0 && !isRegistered(email)){
            Account account = new Account();
            account.setEmail(email);
            account.setPassword(password);
            userMapper.insertSelective(account);
            return true;
        }
        return false;
    }

    @Override
    public Boolean isRegistered(String email) {
        Account account = new Account();
        account.setEmail(email);
        Account dataBaseAccount = userMapper.selectOne(account);
        if(dataBaseAccount == null){
            return false;
        }
        return true;
    }

    @Override
    public String login(String email, String password) {
        Account account = new Account();
        account.setEmail(email);
        account.setPassword(password);
        Account dataBaseAccount = userMapper.selectOne(account);
        if(dataBaseAccount != null){
            return email;
        }
        return null;
    }

    @Override
    public String info(String token) {
        Token tokenTemplate = new Token();
        tokenTemplate.setToken(token);
        Token result = tokenMapper.selectOne(tokenTemplate);
        if(result != null){
            return result.getEmail();
        }
        return null;
    }

    @Override
    public String createToken(String email, String password) {
        Token token = new Token();
        token.setEmail(email);
        Token lastToken = tokenMapper.selectOne(token);
        String encodeToken = Base64Util.encode(email + FLAG + password);
        if(lastToken == null){
            token.setToken(encodeToken);
            tokenMapper.insertSelective(token);
        } else {
            token.setId(lastToken.getId());
            token.setToken(encodeToken);
            tokenMapper.updateByPrimaryKey(token);
        }
        return encodeToken;
    }

}
